<template>
  <div class="echarts-base-comp" v-if="visible">
    <div :ref="refName" class="echarts-base-container"></div>
  </div>
</template>

<script>
export default {
  name: 'echartsBase',
  props: {
    // 图表配置参数
    options: {
      type: Object,
      default: () => ({}),
    },
    visible: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 图表实例
      myCharts: null,
      chartsDom: null,
      refName: `histogram${this.$getRandomNum()}`,
      timer: null,
      count: 0,
    };
  },
  watch: {
    visible(data) {
      if (!data) {
        if (this.myCharts) {
          this.myCharts.dispose();
          this.myCharts = null;
          this.addResizeEvt();
        }
        return;
      }
      !this.chartsDom && this.init();
      this.removeResize();
    },
    options: {
      deep: true,
      // immediate: true,
      handler: function (val) {
        if (this.$checkType(val) === 'object') {
          this.setOption(val, true);
        }
      }
    }
  },
  mounted() {
    this.init();
    this.addResizeEvt();
  },
  beforeDestroy() {
    this.removeResize();
  },
  methods: {
    /**
     * 初始化图表
     */
    init() {
      this.chartsDom = this.$refs[this.refName];
      if (!this.chartsDom) return;
      this.myCharts = this.$echarts.init(this.chartsDom);
      this.setOption(this.options);
    },
    /**
     * 设置echarts配置
     * @param data {Object} 配置参数
     * @param notMerge {Boolean} 默认合并两个数据
     */
    setOption(data = {}, notMerge = false) {
      if (this.count > 100) {
        this.timer && clearTimeout(this.timer);
        return;
      }
      if (!this.myCharts) {
        this.count++;
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.setOption(data, notMerge);
        }, 50);
        return;
      }
      this.myCharts.setOption(data, notMerge);
    },
    /**
     * 图表resize
     */
    handleResize() {
      this.myCharts && this.myCharts.resize();
    },
    /**
     * 监听图表resize
     */
    addResizeEvt() {
      window.addEventListener('resize', this.handleResize);
    },
    /**
     * 移除图表监听
     */
    removeResize() {
      window.removeEventListener('resize', this.handleResize);
    }
  }
};
</script>

<style scoped lang="scss">
.echarts-base-comp {
  width: 100%;
  height: 100%;
  .echarts-base-container {
    width: 100%;
    height: 100%;
  }
}
</style>
